package servlets;

import htmlWriter.HtmlWriter;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class servletHome
 */
public class servletHome extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Map<String,Method> calllableMethods= new HashMap<String, Method>();
	
    private HtmlWriter m_HtmlWriter = new HtmlWriter();
    
    static
    {
    	Method[] methods = HtmlWriter.class.getDeclaredMethods();
    	for (Method method : methods)
		{
			if(method.getModifiers()==Modifier.PUBLIC && method.getParameterTypes().length==0)
			{
				calllableMethods.put(method.getName(),method);
			}
		}
    }
    

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		 processRequest(request, response);
	}
	
	protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String theAction = request.getParameter("action");
		try {
			if(calllableMethods.containsKey(theAction))
			{
				out.println("{\"DivMainContainer\":\"" + calllableMethods.get(theAction).invoke(m_HtmlWriter) + "\"}");
	        }
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		finally
		{            
			out.close();
		}
	}
}